package com.lwl.rabbitmq.workqueues;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Worker {



    private final static String queue_name = "WorkQueues";
    private final static String host = "127.0.0.1";


    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(queue_name,true,false,false,null);
        //accept only one unack-ed message at a time (see below)
        channel.basicQos(1);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println("received " + message);
				doWork(message);
                //显示确认消息接收并处理完成	
				channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        //不自动确认消息到达并处理完成
        boolean autoAck = false ; 
        channel.basicConsume(queue_name,autoAck,defaultConsumer);
        System.out.println("[*] Waiting for message. To exit press ctrl+c");
    }

    private static void doWork(String task){
    	try {
    		for (char ch: task.toCharArray()) {
                if (ch == '.') Thread.sleep(5000);
            }
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        
    }    




}
